<?php

namespace App\Service\Cruise\Check;

use App\Models\Common\ResourcesModel;
use App\Models\Cruise\CruiseCheckDetailModel;
use App\Models\Cruise\CruiseCheckErrorModel;
use App\Models\Cruise\CruiseCheckTaskGroupModel;
use App\Models\Cruise\CruiseCheckTaskModel;
use App\Models\Cruise\CruiseOrderExamineLogModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Cruise\CruiseOrderProcessModel;
use App\Models\Cruise\CruiseTaskOrderMappingModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Service\BaseService;
use App\Service\Cruise\Disinfect\CruiseDisinfectService;
use Exception;
use Illuminate\Support\Facades\DB;

class CruiseCheckTaskService extends BaseService
{
    /**
     * @param int $id
     * @param int $userId
     * @param bool $single 单个删除
     * @param int $invalidType
     * @param string $explain
     * @param array $video
     * @param array $power  用来控制权限
     * @return void
     * @throws Exception
     */
    public static function orderCancel(int $id, int $userId, bool $single = true, int $invalidType = 0, string $explain = '', array $video = [], array $power = [CruiseOrderModel::STATUS_INIT, CruiseOrderModel::STATUS_NOT_SUBMIT, CruiseOrderModel::STATUS_COLLECTED,])
    {
        $cruiseOrderModel = CruiseOrderModel::query()->where('id', $id)->with(['checkTaskDetailRel'])->first();
        if (!$cruiseOrderModel) {
            self::throwErr('不存在的稽核订单');
        }

        $status = $cruiseOrderModel->status;

        if (!in_array($status, $power)) {
            return;
        }

        DB::beginTransaction();

        //作废订单
        CruiseOrderModel::query()
            ->where('id', $id)
            ->update([
                'status'       => CruiseOrderModel::STATUS_CLOSED,
                'relationCode' => '', // 解绑服务单号
            ]);

        if ($userId != 0) {
            // 作废任务组关联服务单号
            CruiseCheckTaskGroupModel::query()
                ->where('relationCode', $cruiseOrderModel->relationCode)
                ->update([
                    'relationCode' => ''
                ]);
        }

        CruiseCheckDetailModel::query()
            ->where('orderId', $id)
            ->update([
                'reportResult' => CruiseCheckDetailModel::REPORT_RESULT_CANCEL
            ]);

        //获得任务ID
        $taskId = (int)CruiseTaskOrderMappingModel::query()
            ->where('orderId', $id)
            ->value('taskId');

        CruiseCheckTaskModel::query()
                            ->where('id', $taskId)
                            ->where('endTime', '<=', time()) // task仅在过期的时候，才会变作废
                            ->where('status', '!=', CruiseCheckTaskModel::STATUS_FINISH)
                            ->update([
                                'status' => CruiseCheckTaskModel::STATUS_CANCEL
                            ]);

        //添加日志
        // 插入process记录
        $processId = CruiseOrderProcessModel::query()->create([
            'cruiseOrderId' => $id,
            'step'          => CruiseOrderProcessModel::PROCESS_CANCEL,
            'status'        => CruiseOrderProcessModel::STATUS_OK,
            'type'          => CruiseOrderModel::TYPE_CHECK,
        ])->id;

        // 插入examine记录
        CruiseOrderExamineLogModel::query()->create([
            'processId' => $processId,
            'content'   => '',
            'status'    => CruiseOrderModel::TYPE_CHECK,
        ]);

        CruiseCheckSpecialService::tryCompleteStatus($taskId);

        if ($invalidType != CruiseCheckErrorModel::INVALID_TYPE_MISS && $cruiseOrderModel->type != CruiseTemplateModel::TYPE_6) {
            //生成异常报备单
            $cruiseCheckErrorId = CruiseCheckErrorModel::query()->create([
                'shopId'              => $cruiseOrderModel->shopId,
                'cruiseCheckDetailId' => (int)optional($cruiseOrderModel->checkTaskDetailRel)->id,
                'invalidType'         => $invalidType,
                'conditionExplain'    => $explain,
                'dealResult'          => CruiseCheckErrorModel::DEAL_RESULT_UNTREATED,
            ])->id;

            if (count($video)) {
                //添加视频资源
                ResourcesModel::moduleBusinessSingleResourcesUpdate(
                    ResourcesModel::MODULE_TYPE_CHECK,
                    ResourcesModel::BUSINESS_CHECK_ERROR_REPORT_VIDEO,
                    'reportVideo',
                    $cruiseCheckErrorId,
                    $video
                );
            }
        }

        DB::commit();

        if ($single && $cruiseOrderModel->type != CruiseTemplateModel::TYPE_6) {
            $cruiseOrderDetailModel = CruiseCheckDetailModel::query()->where('orderId', $id)->first();
            (new CruiseCheckFsService($cruiseOrderDetailModel, $cruiseOrderModel))->offlineSingle($userId);
        }

        // 发送NSQ
        CruiseDisinfectService::aboutCruiseOrderChangedPublishNsq('cancelled', $cruiseOrderModel->toArray());
    }
}
